package kz.edu.sdu.itech.pcs.common;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.regex.Pattern;

public class Message {
   public static Pattern REQUEST_PATTERN = Pattern.compile("[a-zA-Z_-]+:[a-zA-Z0-9, .=|-]*");
   protected MessageType type;
   protected HashMap<String, String> args;

   public MessageType getType() {
      return type;
   }

   public void setType(MessageType type) {
      this.type = type;
   }

   public HashMap<String, String> getArgs() {
      if (args == null) {
         args = new HashMap<String, String>();
      }
      return args;
   }

   public void setArgs(HashMap<String, String> args) {
      this.args = args;
   }

   public void addArg(String key, String val) {
      getArgs().put(key, val);
   }

   static String mapToString(HashMap<String, String> args) {
      if (args != null) {
         StringBuffer sb = new StringBuffer();
         int x = 0;
         for (Entry e : args.entrySet()) {
            if (x != 0)
               sb.append(",");
            Entry<String, String> q = e;
            sb.append(q.getKey()).append("=").append(q.getValue());
            x++;
         }
         return sb.toString();
      }
      return "msg=msg";
   }

   protected static HashMap<String, String> readArgs(String line) {
      HashMap<String, String> result = new HashMap<String, String>();
      String st[] = line.split(",");
      for (int i = 0; i < st.length; i++) {
         String pk[] = st[i].split("=");
         result.put(pk[0], pk[1]);
      }
      return result;
   }

   protected boolean read(String line) {
      boolean ok = true;
      if (line != null && line.length() > 0) {
         String st[] = line.split(":");
         type = MessageType.valueOf(st[0]);
         args = readArgs(st[1]);
      } else
         ok = false;
      return ok;
   }

   @Override
   public String toString() {
      return String.format("%s:%s", type.toString(), mapToString(args));
   }
}
